package com.qf.controller;

import com.qf.entity.User;
import com.qf.service.UserService;
import com.qf.service.impl.UserServiceImpl;
import com.qf.utils.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet(name = "UserServlet",urlPatterns = "/userservlet")
public class UserServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        if(username==null||username.trim().length()==0){
            response.sendRedirect("login.jsp");
            return;
        }
        if(password==null||password.trim().length()==0){
            response.sendRedirect("login.jsp");
            return;
        }

        UserService userService=new UserServiceImpl();
        try {
            User user=userService.login(username,password);

            HttpSession session = request.getSession();
            session.setAttribute("user", user);

            response.sendRedirect("list.jsp");

        } catch (Exception e) {
            e.printStackTrace();
            //重定向 login.html
            response.sendRedirect("login.jsp");
        }

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }
}
